package wwy.Controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import wwy.Common.LogicController;
import wwy.Dao.OrderDao;
import wwy.Dto.OrdersDto;
import wwy.Entity.Orders;
import wwy.Service.OrderService;

import java.util.List;

@RestController
@Tag(name = "orders", description = "订单相关" )
@RequestMapping("/orders")
@RefreshScope
public class OrdersController extends LogicController<OrderService, OrderDao, Orders,Long> {
    public OrdersController(OrderService orderService) {super(orderService);}

    @GetMapping("/getUserOrders/{userId}")
    @Operation(summary = "获取用户所有的订单")
    @CircuitBreaker(name="backendA",fallbackMethod = "fallback")
    public List<OrdersDto> getUserOrders(@PathVariable("userId") Long userId){
        return service.getUserOrders(userId);
    }

    @PostMapping("/addOrder")
    @Operation(summary = "添加订单")
    @Transactional
    @CircuitBreaker(name="backendA",fallbackMethod = "fallback")
    public ResponseEntity<String> addOrder(@RequestBody OrdersDto ordersDto){
        service.addNewOrder(ordersDto);
        service.updateOrderItems(ordersDto,service.getNewestOrderId());
        return ResponseEntity.ok("添加成功");
    }
    @PostMapping("/payOrder")
    @Operation(summary = "支付订单")
    @CircuitBreaker(name="backendA",fallbackMethod = "fallback")
    public ResponseEntity<String> payOrder(@RequestParam(value = "orderId")  Long orderId){
        service.payOrder(orderId);
        return ResponseEntity.ok("支付成功");
    }

    public ResponseEntity<String> fallback(Throwable e){
        return ResponseEntity.ok("服务发生错误:"+e.getMessage()+" 暂时不可用，请稍后再试");
    }
}
